package mysql

import (
	"errors"
	"gorm.io/gorm"
	"mypro/dao/mysql"
	"mypro/models"
)

func Login(user *models.User) (err error) {
	oPassword := user.PassWord
	var foundUser models.User
	// 根据用户名从数据库中查找用户
	result := mysql.Db.Where("user_name = ?", user.UserName).First(&foundUser)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return errors.New("user not found")
		}
		return result.Error
	}
	// 对用户输入的密码进行 MD5 加密
	hashedInputPassword := encryptPassword(oPassword)

	// 比较密码
	if foundUser.PassWord != hashedInputPassword {
		return errors.New("invalid password")
	}
	user.UserID = foundUser.UserID
	user.Token = foundUser.Token
	return nil
}
